package com.lagou.config;

import com.lagou.io.Resources;
import com.lagou.pojo.Configuration;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.beans.PropertyVetoException;
import java.io.InputStream;
import java.util.List;
import java.util.Properties;

/**
 * @ClassName: XMLConfigBuilder
 * @Description: TODO
 * @Date: 2021/2/9 15:07
 * @Create by: shuiren
 */
public class XMLConfigBuilder {

    private Configuration configuration;

    public XMLConfigBuilder() {
        configuration = new Configuration();
    }

    /**
     * 该方法就是将配置文件进行解析
     */
    public Configuration parseConfig(InputStream inputStream) throws DocumentException, PropertyVetoException {
        Document document = new SAXReader().read(inputStream);
        Element rootElement = document.getRootElement();
        //为啥用property？  使用的Xparse表达式，表示在此文件中任意位置的property标签都可以被查找到
        List<Element> list = rootElement.selectNodes("//property");
        Properties property = new Properties();
        for (Element e : list) {
            String name = e.attributeValue("name");
            String value = e.attributeValue("value");
            property.put(name, value);
        }

        ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
        comboPooledDataSource.setDriverClass(property.getProperty("driverClass"));
        comboPooledDataSource.setJdbcUrl(property.getProperty("jdbcUrl"));
        comboPooledDataSource.setUser(property.getProperty("username"));
        comboPooledDataSource.setPassword(property.getProperty("password"));
        configuration.setDataSource(comboPooledDataSource);

        // 2.封装mapper
        List<Element> mapperList = rootElement.selectNodes("//mapper");
        for (Element element : mapperList) {
            String path = element.attributeValue("resource");
            InputStream resourceAsStrean = Resources.getResourceAsStrean(path);
            XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(configuration);
            xmlMapperBuilder.parseMapper(resourceAsStrean);
        }

        return configuration;
    }
}
